package com.bw.home.ui

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bw.home.R
import com.bw.home.databinding.ActivityHomeDetailBinding
import com.bw.home.entity.DanMuEntity
import com.bw.home.entity.SimpleVideoEntity
import com.bw.home.intent.DanMuIntent
import com.bw.home.state.DanMuState
import com.bw.home.view.MyBaseCache
import com.bw.home.viewmodel.DanMuViewModel
import com.bw.home.viewmodel.SimpleVideoViewModel
import com.bw.lib_common.ConstValue
import com.bw.lib_mvi.BaseActivity
import com.google.android.material.tabs.TabLayout
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.Danmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import kotlin.random.Random


@Route(path = ConstValue.HOME_DETAIL_PATH)
class HomeDetailActivity : BaseActivity() {
    lateinit var binding: ActivityHomeDetailBinding
    lateinit var vm: DanMuViewModel

    val danMuList: MutableList<DanMuEntity> = mutableListOf()

    @Autowired
    @JvmField
    var data: SimpleVideoEntity? = null

    lateinit var homeDetailDescripteFragment: HomeDetailDescripteFragment
    lateinit var commonFragment: HomeDetailCommentFragment

    //弹幕上下文
    lateinit var mDMContext: DanmakuContext

//    var isSend: Boolean = false

    //弹幕解析器
    private fun getDMParser(): BaseDanmakuParser {
        return object : BaseDanmakuParser() {
            override fun parse(): IDanmakus {
                return Danmakus()
            }
        }
    }

    override fun getRootLayout(): View {
        binding = ActivityHomeDetailBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        vm = ViewModelProvider(this).get(DanMuViewModel::class.java)

        ARouter.getInstance().inject(this)
        binding.homeDetailTab.addTab(binding.homeDetailTab.newTab().setText("简介"))
        binding.homeDetailTab.addTab(binding.homeDetailTab.newTab().setText("评论"))

        val bundle = Bundle()
        bundle.putParcelable(ConstValue.homeDetailData, data)

        commonFragment = HomeDetailCommentFragment()
        commonFragment.arguments = bundle

        homeDetailDescripteFragment = HomeDetailDescripteFragment()
        homeDetailDescripteFragment.arguments = bundle

        supportFragmentManager.beginTransaction()
            .add(R.id.home_detail_fl, homeDetailDescripteFragment).commitAllowingStateLoss()

        Log.d("TagA", "initView: ${data}")

        //发送弹幕请求
        lifecycleScope.launch {
            vm.intents.send(DanMuIntent.getDanMu(0, "${data?.item_id}"))
        }
    }

    override fun initEvent() {
        super.initEvent()
        binding.homeDetailTab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                if (tab?.text == "简介") {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.home_detail_fl, homeDetailDescripteFragment)
                        .commitAllowingStateLoss()
                } else {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.home_detail_fl, commonFragment).commitAllowingStateLoss()
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })

        binding.fullscreenCinemaSw.setOnCheckedChangeListener(object :
            CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttomView: CompoundButton?, isCheck: Boolean) {
                if (isCheck) {
                    val danmakuParser = getDMParser()
                    binding.dmkHomeDetail.prepare(danmakuParser, mDMContext)
                    binding.dmkHomeDetail.resume()
                } else {
                    binding.dmkHomeDetail.stop()
                }
            }
        })

        binding.bulletDmCinemaTv.setOnClickListener {
            val bottom = DanMuDialogFragment()
            bottom.setDanMuListener(object : DanMuDialogFragment.DanMuListener {
                override fun onClick() {
                    if (bottom.et_danmu_home.text.toString().trim() != null) {
                        //发送弹幕
                        lifecycleScope.launch {
                            val entity = DanMuEntity(
                                bottom.et_danmu_home.text.toString().trim(),
                                "",
                                0,
                                "",
                                0,
                                0,
                                "${data?.item_id}",
                                "",
                                0
                            )
                            vm.intents.send(DanMuIntent.sendDanMu(entity))
                        }
                        bottom.close()
                        AddDanMuk(false, bottom.et_danmu_home.text.toString().trim(),binding.dmkHomeDetail.currentTime)
                    } else {
                        ToastUtils.showLong("请输入内容")
                    }
                }
            })
            bottom.show(supportFragmentManager, "DanMuDialogFragment")
        }


        //请求弹幕l
        lifecycleScope.launch {
            vm.state.collect {
                when (it) {

                    is DanMuState.getDanMu -> {
                        danMuList.clear()
                        danMuList.addAll(it.data)
//                        mhandler.post {
//                            danMuList.forEachIndexed { index, it ->
//                                    AddDanMuk(false, it.content,(binding.gsyHomeDetail.duration/ danMuList.size *(index + 1)).toLong())
//                            }
//                        }
                    }

                    is DanMuState.sendDanMu -> {
//                        isSend = true
                        ToastUtils.showLong("发送成功")
                    }

                    is DanMuState.deleteDanMu -> {

                    }

                    else -> {}
                }
            }
        }


    }

    override fun initData() {
        super.initData()
        binding.gsyHomeDetail.setUp(data?.videopath, true, null, null, "")
        binding.gsyHomeDetail.backButton.visibility = View.GONE
//        binding.gsyHomeDetail.startButton.visibility = View.GONE

        binding.gsyHomeDetail.fullscreenButton.setOnClickListener {
            binding.gsyHomeDetail.startWindowFullscreen(this, true, true)
        }
        binding.gsyHomeDetail.isShowFullAnimation = true
        //自动播放
//        binding.gsyHomeDetail.startButton.performClick()
        initDM()

        mhandler.postDelayed(object : Runnable {
            override fun run() {
                danMuList.forEach {
                    lifecycleScope.launch {
                        AddDanMuk(false, it.content)
                    }
                }
                mhandler.postDelayed(this, 1000)
            }
        }, 1000)
    }

    //缓存代理
    private val mBaseCacheStuffer: BaseCacheStuffer.Proxy = object : BaseCacheStuffer.Proxy() {
        override fun prepareDrawing(danmaku: BaseDanmaku?, fromWorkerThread: Boolean) {

        }

        override fun releaseResource(danmaku: BaseDanmaku?) {
            danmaku?.tag = null
        }

    }


    private val mhandler = Handler()
    private fun initDM() {
        mDMContext = DanmakuContext.create()
        mDMContext.setDuplicateMergingEnabled(true)
            .setScrollSpeedFactor(1.2f)
            .setScaleTextSize(1.2f)
            //导入自定义view
            .setCacheStuffer(MyBaseCache(this), mBaseCacheStuffer)
        if (binding.dmkHomeDetail != null) {
            val danmupaser = getDMParser()
            binding.dmkHomeDetail.setCallback(object : DrawHandler.Callback {
                override fun prepared() {
                    binding.dmkHomeDetail.start()
                }

                override fun updateTimer(timer: DanmakuTimer?) {

                }

                override fun danmakuShown(danmaku: BaseDanmaku?) {

                }

                override fun drawingFinished() {

                }

            })
            binding.dmkHomeDetail.prepare(danmupaser, mDMContext)
            binding.dmkHomeDetail.enableDanmakuDrawingCache(true)
        }
    }

    private var mcontentcoloBg = arrayListOf("#BAE6E1", "#A8A8A8", "#D7BEBE")
    private fun AddDanMuk(isLive: Boolean, content: String,time:Long=binding.dmkHomeDetail.currentTime) {
        val danmaku: BaseDanmaku =
            mDMContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        if (danmaku == null || mDMContext == null) {
            return
        }
        //设置参数
        val map: MutableMap<String, Any> = HashMap(16)
        map["content"] = content
        var bitmap: Bitmap =
            BitmapFactory.decodeResource(resources, R.drawable.home_danmu)
        map["bitmap"] = bitmap
        var random = Random
        var randomNum = random.nextInt(mcontentcoloBg.size)
        map["color"] = mcontentcoloBg.get(randomNum)
        danmaku.tag = map
        danmaku.text = ""
        danmaku.isLive = isLive
        danmaku.textSize = 0f
        danmaku.textColor = Color.WHITE
        danmaku.time = time
        danmaku.padding = 10
        danmaku.priority = 1

        binding.dmkHomeDetail.addDanmaku(danmaku)
    }
}